package cn.bqjr.eily.shiro.spring.boot;

import cn.bqjr.eily.redis.spring.boot.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class RedisLoginRetryCache implements LoginRetryCache {

    private static final String incorrectLogin = "incorrectLogin";

    @Autowired
    private IRedisService redisService;

    private String getCacheKey(String loginId) {
        return incorrectLogin + ":" + loginId;
    }

    @Override
    public AtomicInteger getRetryCount(String loginId) {
        String cacheKey = getCacheKey(loginId);
        if (redisService.exist(cacheKey)) {
            AtomicInteger retryCount = redisService.get(cacheKey, AtomicInteger.class);
            if (null == retryCount || retryCount.intValue() < 0) {
                retryCount = new AtomicInteger(0);
                redisService.put(cacheKey, retryCount);
            }
            return retryCount;
        }
        return new AtomicInteger(0);
    }

    @Override
    public void updateRetryCount(String loginId, AtomicInteger retryCount, Long expires) {
        updateRetryCount(loginId, retryCount);
        expire(loginId, expires);
    }

    @Override
    public void updateRetryCount(String loginId, AtomicInteger retryCount) {
        String cacheKey = getCacheKey(loginId);
        Long expire = redisService.getExpire(cacheKey, TimeUnit.MILLISECONDS);
        if (expire >= 0) {
            redisService.put(cacheKey, retryCount, expire);
        } else {
            redisService.put(cacheKey, retryCount);
        }
    }

    @Override
    public void expire(String loginId, Long expires) {
        redisService.expire(getCacheKey(loginId), expires);
    }

    @Override
    public void delete(String loginId) {
        redisService.delete(getCacheKey(loginId));
    }
}
